<template>
  <div class="app-container">
    <div style="background-color: #fff">
      <div class="container-module" style="padding-bottom: 0">
        <el-form :inline="true" class="search-form" size="small">
          <el-row style="display: flex">
            <div style="flex: 1">
              <el-form-item class="search-form-item" label="分类名称" style="margin: 5px 0">
                <el-input clearable placeholder="请输入类目名称" v-model="searchForm.name" class="input-with-select">
                </el-input>
              </el-form-item>
              <el-form-item class="search-form-item" label="类目层级" style="margin: 5px 0">
                <el-select clearable v-model="searchForm.level" placeholder="请选择类目层级">
                  <el-option v-for="item in [
                      { name: '一级类目', id: 1 },
                      { name: '二级类目', id: 2 },
                      { name: '三级类目', id: 3 },
                    ]" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div style="padding: 5px 0">
              <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="getcatelist">查询</el-button>
                <el-button size="small" type="primary" icon="el-icon-refresh" @click="resetting">重置</el-button>
                <el-button v-if="!searchDisplay" type="warning" icon="el-icon-caret-bottom"
                  @click="searchDisplay = true">展开</el-button>
                <el-button v-else type="warning" icon="el-icon-caret-top" @click="searchDisplay = false">收起</el-button>
              </el-form-item>
            </div>
          </el-row>
          <el-row v-if="searchDisplay" style="display: flex">
            <el-form-item class="search-form-item" label="时间范围" style="margin: 5px 0">
              <el-date-picker v-model="create_time" type="datetimerange" @change="create_timeWay"
                value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                align="right">
              </el-date-picker>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <el-divider></el-divider>
      <div style="padding: 0 20px 20px">
        <div class="marginBottom">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="16">
              <div class="left-panel">
                <el-button icon="el-icon-circle-plus-outline" type="primary" size="small" v-hasPermi="'Application/add'"
                  @click="goodsadd()">添加分类</el-button>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8">
              <div class="right-panel el-button-group">
                <el-button class="" icon="el-icon-refresh" size="mini" @click="refresh"></el-button>
                <el-dropdown trigger="click" :hide-on-click="false">
                  <span class="el-dropdown-link">
                    <el-button class="" icon="el-icon-s-operation" size="mini"></el-button>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="fruit in allTableThead" :key="fruit">
                      <el-checkbox v-model="checkboxTableThead"
                        :label="fruit">{{ tableTheadOptions[fruit].label }}</el-checkbox>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-row :gutter="20">
          <el-col class="no_pagination_single_card">
            <el-table ref="tablerefs" v-loading="loading" :data="tableData" :header-cell-style="{
                'background-color': '#e5eeff',
                color: '#515a6e',
                'font-weight': '400',
                height: '50px',
              }" style="width: 100%; border-radius: 5px" row-key="id"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" height="100%">
              >
              <el-table-column v-for="fruit in tableThead" :key="fruit" :label="tableTheadOptions[fruit].label"
                align="center" :width="
                  tableTheadOptions[fruit].width
                    ? tableTheadOptions[fruit].width + 'px'
                    : 'auto'
                " style="color: #303133">
                <template slot-scope="scope">
                  <div v-if="fruit == 'parent_id'">
                    {{
                      scope.row.level == 1
                        ? "一级类目"
                        : scope.row.level == 2
                        ? "二级类目"
                        : "三级类目"
                    }}
                  </div>
                  <span v-else>
                    <el-tooltip placement="top-start" :content="scope.row[fruit] +''">
                      <div class="one_line_hidden">
                        {{ scope.row[fruit] ? scope.row[fruit] : "-" }}
                      </div>
                    </el-tooltip>
                  </span>
                </template>
              </el-table-column>

              <el-table-column fixed="right" prop="address" label="操作" align="center" width="240px">
                <template slot-scope="scope">
                  <el-button v-if="scope.row.level <= 2" v-hasPermi="'Application/add'" type="text" size="mini"
                    @click="goodsadd(scope.row)">
                    添加子级分类
                  </el-button>
                  <el-divider v-if="scope.row.level <= 2" direction="vertical"></el-divider>
                  <el-button v-hasPermi="'Application/edit'" type="text" size="mini"
                    @click="editapplocation(scope.row)">
                    编辑
                  </el-button>
                  <el-button type="text" size="small" @click="deletesupplier(scope.row)">
                  删除
                </el-button>
                </template>
              </el-table-column>
            </el-table></el-col>
          <el-col>
            <pagination v-show="total > 0" :total="total" :page.sync="searchForm.page" :limit.sync="searchForm.count"
              @pagination="getcatelist" />
          </el-col>
        </el-row>
      </div>
    </div>
    <el-drawer id="drawer" :modal-append-to-body="false" :append-to-body="true" title="添加分类" size="60%"
      :wrapperClosable="false" :withHeader="false" :visible.sync="adddialogVisible"
      :show-close="false">
      <div style="position: relative" v-loading="addPutLoading">
        <div class="drawerTitle" id="drawerTitle">
          <span>添加类目</span>
          <div class="close" @click="closeWay">
            <i class="el-icon-close" style="font-size: 24px;"></i>
          </div>
        </div>
        <el-alert id="prompt_explanation" style="margin-bottom: 20px;padding: 15px;" title="说明：文章分类主要用于平台对用户的文章分类管理！"
          type="warning" :closable="false">
        </el-alert>
        <el-scrollbar wrap-style="overflow-x:hidden;" :style="'height:' + reduce">
          <el-row v-if="!dialogVisible">
            <el-form ref="form" :rules="rules" :model="form" label-width="100px">
              <!-- <el-col :span="12">
                <el-form-item label="类目图标" prop="category_image">
                  <logo-upload
                    :single-file="form.category_images"
                    :show-file-list="false"
                    accept="image/jpeg, image/png"
                    tipText="仅支持.jpg、.png、.jpeg格式，图大小100px*100px；"
                    @uploadCallback="logoCallback"
                  />
                </el-form-item>
              </el-col> -->
              <el-col v-if="form.parent_id" :span="24">
                <el-form-item label="分类上级" prop="article_name">
                  <span>{{parent}}</span>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="分类名称" prop="name">
                  <el-input size="small" placeholder="请输入分类名称" v-model="form.name"
                    style="width: calc(100% - 50px)"></el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="12">
                <el-form-item label="类目排序" prop="sort">
                  <el-input
                    size="small"
                    placeholder="请输入类目排序"
                    v-model="form.sort"
                    style="width: calc(100% - 50px)"
                  ></el-input>
                </el-form-item>
              </el-col> -->
              <!-- <el-col :span="24">
                <el-form-item label="类目状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio :label="1">开启</el-radio>
                    <el-radio :label="2">关闭</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col> -->
              <el-col :span="24">
                <el-form-item label="分类备注" prop="remark">
                  <el-input type="textarea" placeholder="请输入..." v-model="form.remark" style="width: calc(100% - 50px)"
                    :autosize="{ minRows: 4, maxRows: 6 }"></el-input>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
          <!-- 编辑 -->
          <el-row v-else>
            <el-form ref="forms" :rules="ruless" :model="forms" label-width="100px">
              <el-col :span="24">
                <el-form-item label="父级分类" prop="parent_id" v-if="forms.level !== 1">
                  <el-cascader v-model="values" :options="tableData" :props="{
                      expandTrigger: 'hover',
                      checkStrictly: true,
                      value: 'id',
                      label: 'name',
                    }" @change="handleChanges" :placeholder="levedplace"
                    style="width: calc(100% - 50px)"></el-cascader>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="分类名称" prop="name">
                  <el-input size="small" placeholder="请输入分类名称" v-model="forms.name"
                    style="width: calc(100% - 50px)"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="分类备注" prop="remark">
                  <el-input type="textarea" placeholder="请输入..." v-model="forms.remark"
                    style="width: calc(100% - 50px)"></el-input>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>
        </el-scrollbar>
        <el-row style="margin: 20px 0">
          <el-col v-if="!dialogVisible" :span="24" style="text-align: right; padding-right: 30px">
            <el-button @click="closeWay">取消</el-button>
            <el-button :loading="addPutLoading" type="primary" @click="submitForms('form')">保存</el-button>
          </el-col>
          <el-col v-else :span="24" style="text-align: right; padding-right: 30px">
            <el-button @click="closeWay">取消</el-button>
            <el-button :loading="addPutLoading" type="primary" @click="submitForm('forms')">保存</el-button>
          </el-col>
        </el-row>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import LogoUpload from "@/components/FileUpload";
  import {
    getCateLists,
    SaveAgreementCate,
    deleteAgree
  } from "@/api/activity/agreement";
  const tableTheadOption = {
    id: {
      label: "ID",
      field: "id",
      width: 130,
    },
    parent_id: {
      label: "分类层级",
      field: "parent_id",
      width: 160,
    },
    name: {
      label: "分类名称",
      field: "name",
      width: 160,
    },
    agreementCount: {
      label: "文章数量",
      field: "agreementCount",
      width: 160,
    },
    created_at: {
      label: "创建时间",
      field: "created_at",
      width: 160,
    },
    // updated_at: {
    //   label: "更新时间",
    //   field: "updated_at",
    //   width: 150,
    // },
    remark: {
      label: "备注",
      field: "remark",
    },
  };

  const allTableThead = [
    "id",
    "parent_id",
    "name",
    "agreementCount",
    // "sort",
    "created_at",
    // "updated_at",
    "remark",
  ];
  const defaultTableThead = [
    "id",
    "parent_id",
    "name",
    "agreementCount",
    // "sort",
    "created_at",
    // "updated_at",
    "remark",
  ];
  export default {
    name: "application",
    components: {
      LogoUpload
    },
    data() {
      return {
        parent:'',
        searchDisplay: false,
        reduce: 0,
        coverImgList: [],
        value: "",
        values: [],
        levedplace: "0",
        // 修改提交按钮加载
        addPutLoading: false,
        adddialogVisible: false,
        dialogVisible: false, //true是编辑
        currentPage4: 1, //页码
        rules: {
          name: [{
            required: true,
            message: "请输入类目名称",
            trigger: "blur"
          }, ],
          status: [{
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: "change",
          }, ],

        }, //表单验证
        ruless: {
          name: [{
            required: true,
            message: "请输入类目名称",
            trigger: "change"
          }, ],
          parent_id: [{
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请选择上级"));
              }
              callback();
            },
            trigger: "change",
          }, ],
          status: [{
            required: true,
            validator: (rule, value, callback) => {
              callback();
            },
            trigger: "change",
          }, ],

        }, //表单验证
        forms: {
          id: "",
          parent_id: "",
          name: "",
          remark: "",
          sort: '',
          status: 1
        },
        form: {
          id: "",
          parent_id: 0,
          name: "",
          remark: "",
          sort: '',
          status: 1
        },
        searchForm: {
          level: "", //层级
          page: 1,
          count: 10,
          name: "", //名称
          end_time: "",
          start_time: "",
        },
        tableData: [],
        loading: true, //刷新
        tableKey: 1, // table key
        tableTheadOptions: tableTheadOption,
        allTableThead: allTableThead,
        tableThead: defaultTableThead, // 默认表头
        checkboxTableThead: defaultTableThead, // 默认表头值
        total: 0,
        drawer: false,
        create_time: [],
      };
    },
    watch: {
      checkboxTableThead(valArr) {
        this.tableThead = this.allTableThead.filter(
          (i) => valArr.indexOf(i) >= 0
        );
        this.tableKey = this.tableKey + 1; // 为了保证table 每次都会重渲
        this.$nextTick(() => {
          this.$refs.tablerefs.doLayout();
        });
      },
    },
    mounted() {
      this.getcatelist(); //类目列表
    },
    methods: {
      create_timeWay(vla) {
        this.searchForm.start_time = vla[0];
        this.searchForm.end_time = vla[1];
      },
      // 关闭抽屉执行
      handleClose() {
        this.adddialogVisible = false;
        if (this.dialogVisible) {
          this.dialogVisible = false;
        }
      },

      closeWay() {
        this.form = {
          id: "",
          parent_id: "",
          name: "",
          remark: "",
          status: 1,
          sort: "",
        };
        this.forms = {
          id: "",
          parent_id: 0,
          name: "",
          remark: "",
        };
        console.log( this.form,'---------')
        this.handleClose();


        // this.$nextTick(() => {
        //   if (this.$refs.form) {
        //     this.$refs.form.resetFields();
        //   }
        //   if (this.$refs.forms) {
        //     this.$refs.forms.resetFields();
        //   }
        // });
      },
      // 刷新
      refresh() {
        this.loading = true;
        this.getcatelist();
      },
      resetting() {
        this.searchForm = {
          level: "", //层级
          page: 1,
          count: 10,
          name: "", //名称
          end_time: "",
          start_time: "",
        };
        this.create_time = [];
        this.getcatelist();
      },
      //类目列表
      getcatelist() {
        this.loading = true;
        getCateLists(this.searchForm).then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.loading = false;
            return this.$messages.error(res.msg);
          }
          this.tableData = res.data;
          // this.total = res.data.total;
          // this.tableData.forEach((item) => {
          //   this.coverImgList.push(item.category_image);
          // });
          this.loading = false;
        });
      },
      //编辑
      editapplocation(row) {
        this.forms = JSON.parse(JSON.stringify(row));
        // let obj = {
        //   url: row.category_image,
        // };
        // this.forms.category_images = obj;
        // console.log(this.forms)
        var arr = this.forms.ids.split(",");
        this.values = [];
        arr.forEach((item) => {
          this.values.push(Number(item));
        });
        this.values = this.values.reverse();
        this.levedplace = String(row.parent_id);
        this.dialogVisible = true;
        this.adddialogVisible = true;
        this.nextTickWay("drawer", "drawerTitle", "prompt_explanation");
      },
      //添加
      goodsadd(row) {
        if (row) {
          console.log(row)
          this.form.parent_id = row.id;
        this.parent = row.name
        } else {
          this.form.parent_id = "";
        }
        this.adddialogVisible = true;
        this.nextTickWay("drawer", "drawerTitle", "prompt_explanation");
      },
      nextTickWay(idName1, idName2, idName3) {
        this.$nextTick(() => {
          var adddialogVisible = document.getElementById(idName1);
          var drawerTitle = document.getElementById(idName2);
          var prompt_explanation = document.getElementById(idName3);
          this.reduce =
            adddialogVisible.offsetHeight -
            (prompt_explanation.offsetHeight + drawerTitle.offsetHeight + 100) +
            "px";
        });
      },
      //选中
      // handleChange(value) {
      //   console.log(value);
      //   const length = value.length;
      //   const lastValue = value[length - 1];
      //   this.form.parent_id = lastValue;
      // },
      //select
      handleChanges(value) {
        const length = value.length;
        const lastValue = value[length - 1];
        this.forms.parent_id = lastValue;
      },
      //编辑表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addPutLoading = true;
            this.forms.article_image = ''
            SaveAgreementCate(this.forms)
              .then((res) => {
                if (res.code !== 200 || res.status !== 1) {
                  this.addPutLoading = false;
                  this.adddialogVisible = false
                  return this.$messages.error(res.msg);
                }
                this.adddialogVisible = false
                this.addPutLoading = false;
                this.$messages.success("编辑成功");
                this.dialogVisible = false;
                this.getcatelist();
              })
              .catch(() => {
                this.addPutLoading = false;
              });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      //添加表单
      submitForms(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addPutLoading = true;
            SaveAgreementCate(this.form)
              .then((res) => {
                if (res.code !== 200 || res.status !== 1) {
                  this.addPutLoading = false;
                  return this.$messages.error(res.msg);
                }
                this.addPutLoading = false;
                this.$messages.success("添加成功");
                this.adddialogVisible = false;
                this.getcatelist();
              })
              .catch(() => {
                this.addPutLoading = false;
              });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      // 文件上传回调
      logoCallback(singleFile) {
        this.form.category_images = singleFile;
        this.form.category_image = singleFile.url;
        this.forms.category_images = singleFile;
        this.forms.category_image = singleFile.url;
      },
      //删除
      deletesupplier(row) {
        this.$confirm("此操作将删除该分类, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
          deleteAgree({id:row.id}).then((res)=>{
            if(res.code==200) {
              this.$messages({
                type: "success",
                message: res.msg,
              });
            this.getcatelist();
            }else{
              this.$messages({
                type: "error",
                message: res.msg,
              });
            }
            
          })
          })
          .catch(() => {
            this.$messages({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      //页码
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
      },
      //点击搜索
      search() {
        console.log(this.query, "搜索的数据");
        this.$messages({
          type: "success",
          message: "查询成功!",
        });
      },
    },
  };
</script>

<style lang="scss" scoped>
  .title {
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    font-size: 16px;
    line-height: 16px;
  }

  .sn {
    color: #606266;
    font-size: 13px;
  }

  .demo-table-expand {
    display: flex;
    justify-content: start;
    flex-wrap: wrap;
    color: #515a6e;

    div {
      width: 30%;
      height: 40px;
      text-align: center;
      line-height: 40px;
      font-size: 12px;
    }
  }

  .marginTop {
    padding: 0 15px !important;
  }
</style>
